<template>
    <div v-loading="loading" style="width: 100%">
        <SavePage :title="`${typeName}养护工程`">
            <template slot="buttons">
                <BaseButton :disabled="submitDisabled" :loading="submitLoading" @click="submit()">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips title="工程信息" :required="true" />
                <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="88px">
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="项目名称" prop="projectId">
                                <ProjectSelect :value.sync="form.projectId" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="工程时间" prop="date">
                                <el-date-picker
                                    v-model="form.date"
                                    size="small"
                                    type="daterange"
                                    value-format="yyyy-MM-dd"
                                    :editable="false"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="工程量" prop="workAmount">
                                <el-input v-model.trim="form.workAmount" clearable placeholder="支持小数点后2位" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="单位" prop="arithmeticalUnit">
                                <el-input v-model.trim="form.arithmeticalUnit" clearable placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="公路名称" prop="roadCode">
                                <RoadSelect :value.sync="form.roadCode" @change="getRoadName" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="方向" prop="direction">
                                <el-select v-model="form.direction" clearable placeholder="请选择" style="width: 100%" @change="resetLocation">
                                    <el-option v-for="item in directionOptions" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="养护位置" prop="locationType">
                                <el-select
                                    v-model="form.locationType"
                                    :disabled="!form.roadCode || !form.direction"
                                    placeholder="请选择"
                                    style="width: 100%"
                                    @change="resetLocation"
                                >
                                    <el-option v-for="item in locationOptions" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col v-if="form.locationType === 1" :xl="6" :lg="8">
                            <el-form-item label="设施名称" prop="facilityCode">
                                <FacilitySelect
                                    :value.sync="form.facilityCode"
                                    :props="facilityProps"
                                    collapse-tags
                                    :params="params"
                                    @change="getFacilityName"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="form.locationType === 2" :xl="6" :lg="8">
                            <el-col :span="14" style="padding: 0">
                                <el-form-item label="桩号" prop="stakeStart1">
                                    <el-input
                                        v-model.trim="form.stakeStart1"
                                        :disabled="!form.roadCode || !form.direction"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="form.stakeStart2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" style="padding: 0">
                                <el-form-item
                                    class="spe-item"
                                    label-width="30px"
                                    label="+"
                                    prop="stakeStart2"
                                    :rules="useCheckStake(form.roadCode, form.direction, form.stakeStart1, form.roadStake)"
                                >
                                    <el-input v-model.trim="form.stakeStart2" maxlength="3" :disabled="!form.stakeStart1" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-col>

                        <el-col v-if="form.locationType === 3" :xl="12" :lg="16">
                            <el-col :span="7" style="padding: 0">
                                <el-form-item label="桩号范围" prop="stakeStart1">
                                    <el-input
                                        v-model.trim="form.stakeStart1"
                                        :disabled="!form.roadCode || !form.direction"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="form.stakeStart2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5" style="padding: 0">
                                <el-form-item
                                    class="spe-item"
                                    label-width="30px"
                                    label="+"
                                    prop="stakeStart2"
                                    :rules="useCheckStake(form.roadCode, form.direction, form.stakeStart1, form.roadStake)"
                                >
                                    <el-input v-model.trim="form.stakeStart2" :disabled="!form.stakeStart1" maxlength="3" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="7" style="padding: 0">
                                <el-form-item class="spe-item" label-width="50px" label="~" prop="stakeEnd1">
                                    <el-input
                                        v-model.trim="form.stakeEnd1"
                                        :disabled="!form.roadCode || !form.direction"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="form.stakeEnd2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5" style="padding: 0">
                                <el-form-item
                                    class="spe-item"
                                    label-width="30px"
                                    label="+"
                                    prop="stakeEnd2"
                                    :rules="useCheckStake(form.roadCode, form.direction, form.stakeEnd1, form.roadStake)"
                                >
                                    <el-input v-model.trim="form.stakeEnd2" :disabled="!form.stakeEnd1" maxlength="3" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="工程内容">
                                <el-input v-model="form.workContent" type="textarea" maxlength="200" show-word-limit clearable placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="是否对外招标" label-width="120px" prop="externalBidding">
                                <el-radio-group v-model="form.externalBidding" @change="resetValidate">
                                    <el-radio :label="0">否</el-radio>
                                    <el-radio :label="1">是</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="form.externalBidding === 1" :xl="6" :lg="8">
                            <el-form-item label="合同编号" prop="contractNo">
                                <el-input v-model.trim="form.contractNo" maxlength="50" clearable placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="form.externalBidding === 1" :xl="6" :lg="8">
                            <el-form-item label="合同金额" prop="contractMoney">
                                <el-input v-model.trim="form.contractMoney" maxlength="50" clearable placeholder="支持小数点后两位">
                                    <span slot="suffix" class="el-input__unit input-unit">元</span>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="form.externalBidding === 0" :xl="6" :lg="8">
                            <el-form-item label="养护部门" prop="orgId">
                                <OrgSelect :value.sync="form.orgId" @change="orgChange" />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="form.externalBidding === 0" :xl="6" :lg="8">
                            <el-form-item label="养护人员" prop="maintStaff">
                                <el-select
                                    v-model="form.maintStaff"
                                    :disabled="userDisabled"
                                    clearable
                                    multiple
                                    filterable
                                    placeholder="请选择"
                                    style="width: 100%"
                                >
                                    <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <TitleTips title="关联缺陷病害">
                    <BaseButton slot="button" type="text" icon="el-icon-s-order" @click="handleDefect">缺陷病害</BaseButton>
                </TitleTips>

                <!-- 已经关联缺陷列表 -->
                <DefectTable :list.sync="defectList" />

                <FileUpload ref="fileUpload" :list="form.annexList" @load="handleLoad" />
            </template>
        </SavePage>

        <DefectFormDialog ref="defectFormDialog" :visible.sync="defectFormVisible" :defect-list="defectList" @submit="getDefect" />
    </div>
</template>

<script>
import { isNumber2 } from '@/utils/validate'
import { OrgModel, MaintenanceProjectModel } from '@/models'
import DefectFormDialog from './components/DefectFormDialog'
import DefectTable from './components/DefectTable'
import FileUpload from '../detail/components/FileUpload'
import { DirectionOptions, LocationOptions, BooleanOptions } from '@/config/constants'
import useCheckStake from '@/hooks/useCheckStake'
import { isInteger } from '@/utils/validate'

export default {
    name: 'MaintenanceProjectAdd',
    components: {
        DefectFormDialog,
        DefectTable,
        FileUpload
    },
    data() {
        return {
            loading: false,
            model: new MaintenanceProjectModel(),
            orgModel: new OrgModel(),
            form: {
                projectId: [],
                workAmount: '',
                arithmeticalUnit: '',
                roadCode: '',
                direction: '',
                facilityCode: [],
                locationType: 1,
                stakeStart1: '',
                stakeStart2: '',
                stakeEnd1: '',
                stakeEnd2: '',
                orgId: [],
                maintStaff: [],
                workContent: '',
                externalBidding: 0,
                contractNo: '',
                contractMoney: ''
            },
            directionOptions: DirectionOptions,
            locationOptions: LocationOptions,
            booleanOptions: BooleanOptions,
            rules: {
                projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
                date: [{ required: true, message: '请选择工程时间', trigger: 'change' }],
                workAmount: [
                    { required: true, message: '请输入工程量', trigger: 'blur' },
                    { validator: this.validNum2, trigger: 'blur' }
                ],
                arithmeticalUnit: [{ required: true, message: '请输入工程量单位', trigger: 'blur' }],
                roadCode: [{ required: true, message: '请选择公路', trigger: 'change' }],
                direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
                facilityCode: [{ required: true, message: '请选择设施', trigger: 'change' }],
                stakeStart1: [
                    { required: true, message: '请输入起始桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                stakeEnd1: [
                    { required: true, message: '请输入结束桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                orgId: [{ required: true, message: '请选择养护部门', trigger: 'change' }],
                maintStaff: [{ required: true, message: '请选择养护人员', trigger: 'change' }],
                locationType: [{ required: true, message: '请选择养护位置', trigger: 'change' }],
                externalBidding: [{ required: true, message: '请选择是否对外招标', trigger: 'change' }],
                contractNo: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
                contractMoney: [
                    { required: true, message: '请输入合同金额', trigger: 'blur' },
                    { validator: this.validNum2, trigger: 'blur' }
                ]
            },
            type: 'add',
            submitLoading: false,
            typeName: '新建',
            defectFormVisible: false,
            defectList: [],
            userOptions: [],
            userDisabled: true,
            facilityProps: {
                value: 'id',
                label: 'name',
                multiple: true
            },
            submitDisabled: false
        }
    },
    computed: {
        // 设施的过滤参数
        params() {
            const params = {
                roadCode: this.form.roadCode,
                direction: this.form.direction
            }
            return params
        }
    },
    async created() {
        this.getQuery()
        this.id && (await this.getDetail())
    },
    methods: {
        validNum(rule, value, callback) {
            if (value && !isInteger(value)) {
                callback(new Error('请输入数字'))
            } else {
                callback()
            }
        },
        handleLoad(value) {
            console.log(value)
            this.submitDisabled = value
        },
        resetLocation() {
            this.$refs['form'].clearValidate(['facilityCode', 'stakeStart1', 'stakeStart2', 'stakeEnd1', 'stakeEnd2'])
            this.form.facilityCode = []
            this.form.stakeStart1 = ''
            this.form.stakeStart2 = ''
            this.form.stakeEnd1 = ''
            this.form.stakeEnd2 = ''
        },
        // 是否投标变化时，清除验证，恢复对应输入框默认值
        resetValidate() {
            this.$refs['form'].clearValidate(['contractNo', 'contractMoney'])
            this.form.contractNo = ''
            this.form.contractMoney = ''
            this.form.orgId = []
            this.form.maintStaff = []
        },
        // 后端还要传设施名称字段
        getFacilityName(val, options) {
            // 后端要设施中文名和经纬度
            this.form.facilityName = ''
            this.form.facilityLngLat = []
            options.forEach((item) => {
                item.children.some((m) => {
                    val.some((v) => {
                        if (m.id === v[1]) {
                            this.form.facilityName += m.name + ','
                            this.form.facilityLngLat.push(m.lngLat)
                            return true
                        }
                    })
                })
            })
            // 把最后一个多余的, 去除
            this.form.facilityName = this.form.facilityName.replace(/,$/, '')
            console.log(this.form.facilityLngLat)
        },
        // 后端还要传公路名称字段
        getRoadName(val, options) {
            this.resetLocation()
            options.some((item) => {
                if (item.code === val) {
                    this.form.roadName = item.name
                    this.form.roadStake = item.roadStake
                    return true
                }
            })
        },
        orgChange(orgIds, isClear = true) {
            if (orgIds.length === 0) {
                return
            }
            this.userDisabled = false
            isClear && (this.form.maintStaff = [])
            const orgId = orgIds[orgIds.length - 1]
            this.getUserByOrg(orgId)
        },
        getUserByOrg(id) {
            this.orgModel.detail(id, { pageSize: 1000 }).then((res = []) => {
                this.userOptions = res.map((item) => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
            })
        },
        getDefect(val) {
            console.log(val)
            this.defectList = val
        },
        handleDefect() {
            this.defectFormVisible = true
            this.$refs['defectFormDialog'].resetForm()
            this.$refs['defectFormDialog'].init(this.type)
        },
        getQuery() {
            this.type = this.$route.query.type || 'add'
            if (this.type === 'edit') {
                this.typeName = '编辑'
                this.loading = true
                this.id = this.$route.query.id
            } else {
                this.typeName = '新建'
                // 新增时，当前用户默认为制表人
                this.defalutUserId = this.$store.getters.avatar.id
                this.form.period = this.$route.query.period
            }
            // 如果有source参数，说明是从缺陷页过来
            const source = this.$route.query.source
            console.log('source>>>', source)
            if (source) {
                const list = localStorage.getItem('flaws')
                this.defectList = JSON.parse(list)
            }
        },
        getDetail() {
            return this.model
                .detail({ id: this.id })
                .then((res) => {
                    const obj = {
                        projectId: res.projectId ? res.projectId.split(',').map(Number) : [],
                        maintStaff: res.maintStaff ? res.maintStaff.split(',').map(Number) : [],
                        date: res.date.split('~'),
                        stakeStart1: res.stakeStart ? res.stakeStart.split('+')[0].replace('K', '') : null,
                        stakeStart2: res.stakeStart ? res.stakeStart.split('+')[1] : null,
                        stakeEnd1: res.stakeEnd ? res.stakeEnd.split('+')[0].replace('K', '') : null,
                        stakeEnd2: res.stakeEnd ? res.stakeEnd.split('+')[1] : null,
                        orgId: res.orgId ? res.orgId.split(',').map(Number) : []
                    }
                    this.form = Object.assign(res, obj)
                    this.defectList = res.defectList
                    this.orgChange(this.form.orgId, false)
                })
                .finally(() => {
                    this.loading = false
                })
        },
        submit() {
            this.submitLoading = true
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let data = JSON.parse(JSON.stringify(this.form))
                    // 把几个参数处理成后端所需要的
                    const obj = {
                        projectId: data.projectId.toString(),
                        maintStaff: data.maintStaff.toString(),
                        date: data.date.join('~'),
                        stakeStart: `K${data.stakeStart1}+` + (data.stakeStart2 || '000'), // +后面桩号无值时默认为000
                        stakeEnd: `K${data.stakeEnd1}+` + (data.stakeEnd2 || '000'),
                        orgId: data.orgId.toString(),
                        defectIds: this.defectList.map((item) => item.id).toString()
                    }
                    // 删掉冗余的defectList字段
                    delete data.defectList

                    // 获取上传的文件信息
                    const annexList = this.$refs['fileUpload'].getFileList()

                    data = Object.assign(data, obj, { annexList })

                    this.model
                        .saveOrUpdate(data)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: this.type === 'edit' ? '修改成功！' : '新建成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                } else {
                    this.submitLoading = false
                }
            })
        },
        validNum2(rule, value, callback) {
            if (value && !isNumber2(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        },
        useCheckStake
    }
}
</script>

<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}

// <ul class="defect-list">
//     <li class="defect-item">
//         <span class="defect-name">2021-4145522</span>
//         <i class="el-icon-close" />
//     </li>
//     <li class="defect-item">
//         <span class="defect-name">2021-4145522</span>
//         <i class="el-icon-close" />
//     </li>
// </ul>
// .defect-list {
//     width: 400px;
//     .defect-item {
//         padding: 4px 16px;
//         margin-bottom: 16px;
//         border: 1px solid #DCDFE6;
//         border-radius: 4px;
//         display: flex;
//         align-items: center;
//         justify-content: space-between;
//         .defect-name {
//             &::before {
//                 display: inline-block;
//                 content: '';
//                 width: 8px;
//                 height: 8px;
//                 margin-right: 4px;
//                 border-radius: 50%;
//                 background-color: #0162FF;
//                 position: relative;
//                 top: -2px;
//             }
//         }
//     }
// }
</style>
